const http = require('http');
const url = require('url')

const students = [
  { id: 3001, name: "小王", age: 18, gender: "男" },
  { id: 3002, name: "小楠", age: 17, gender: "女" },
  { id: 3007, name: "小林", age: 20, gender: "女" },
  { id: 3008, name: "老王大大", age: 19, gender: "男" },
]
function findById(id) {
  return students.filter(item => item.id === id)
}

http.createServer(function (request, response) {
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  response.setHeader('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  response.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });

  let id = url.parse(request.url).query
  id = (id && id.split('=')[1]) * 1
  // console.log(request.url.split(/\?/)[1]);
  // console.log(request.path);
  // console.log(request.url);
  const regex = /\?.*/
  switch (request.url.replace(regex, "")) {
    case "/students":
      response.end(JSON.stringify(students));
      break;
    case "/studentById":
      JSON.stringify(findById(id)) == "[]" ? response.end('查无此人,您必须输入数字3001-3010') : response.end(JSON.stringify(findById(id)))
    default:
      response.end('服务端无数据,请请求students和studentById这两个地址')
      break;
  }
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');